package net.apexcns.core.config;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import net.apexcns.core.util.XmlBindUtil;

@SuppressWarnings("unchecked")
public class ConfigFactory {
	@SuppressWarnings("rawtypes")
	private static Map<Class,Object> instanceMap = new HashMap<Class,Object>();

	public static <T extends Config> T getConfig(Class<T> clazz) {
		T instance = (T) instanceMap.get(clazz);
		if(instance != null) return instance;
		T tmp = null;
		try {
			tmp = clazz.newInstance();
			instance = (T) XmlBindUtil.fromXml(clazz, new File(tmp.getConfigPath()));
			if(tmp.afterBindDefault()) {	// null, "", 0
			}
			instance.afterBind();
		} catch (Exception e) {
			String msg = clazz.getName();
			if(tmp!=null) msg += ", configFile="+tmp.getConfigPath();
			throw new RuntimeException(msg, e);
		}
		return instance;
	}

}
